<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <!-- 编辑器宽高 -->
    <Editor
      style="overflow-y: hidden; height: 100vh"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="deal_change"
    />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot } from '@wangeditor/editor'
import formulaModule from '@wangeditor/plugin-formula'
import markdownModule from '@wangeditor/plugin-md'
import eventBus from '@/eventBus/eventbus'
import { SlateNode } from '@wangeditor/editor'
import { MyButtonMenu } from '@/mylibs/ButtonMenu'
const menu1Conf = {
  key: 'menu_del_img_from_oss', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new MyButtonMenu() // 把 `YourMenuClass` 替换为你菜单的 class
  }
}

// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
Boot.registerModule(formulaModule)
Boot.registerMenu(menu1Conf)
Boot.registerModule(markdownModule)
import putBuffer from '@/api/API_Uploading_Directory_Tree'
import { PATH_wangEditor_img_vid } from '@/mylibs/define'
import { getUuid } from '@/mylibs/functions'
export default {
  components: { Editor, Toolbar },
  data() {
    return { clientHeight: 500 }
  },
  mounted() {
    this.clientHeight = document.body.clientHeight
    window.onresize = () => {
      //屏幕尺寸变化就重新赋值
      return (() => {
        this.clientHeight = document.body.clientHeight
      })()
    }
  },

  methods: {
    // 编辑器内容改变时触发
    deal_change(editor) {
      const headers = editor.getElemsByTypePrefix('header')
      var list = headers.map((header) => {
        const text = SlateNode.string(header)
        const { id, type } = header

        return { id, type, text }
      })

      try {
        eventBus.emit('get_show_title_list', list)
      } catch (e) {}
    }
  },
  setup() {
    // 编辑器实例，必须用 shallowRef
    var editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ''

    const toolbarConfig = {
      insertKeys: {
        index: 0,
        keys: [
          'insertFormula', // “插入公式”菜单
          'editFormula' // “编辑公式”菜单
        ]
      }
    }

    const editorConfig = {
      placeholder: '请输入内容...',
      MENU_CONF: {
        uploadImage: {
          // 自定义上传
          async customUpload(file, insertFn) {
            // file 即选中的文件
            // 自己实现上传，并得到图片 url alt href
            // 最后插入图片
            let path = PATH_wangEditor_img_vid + getUuid() + '/' + file.name
            let { res, ok, err } = await putBuffer('put', path, file, true)
            if (ok) {
              insertFn(res, file.name, res)
            } else {
              this.$Notice.error({ desc: err })
            }
          },
          // 小于该值就插入 base64 格式（而不上传），默认为 0
          base64LimitSize: 5 * 1024 // 5kb
        },
        uploadVideo: {
          // 单个文件的最大体积限制，默认为 10M
          maxFileSize: 3 * 1024 * 1024 * 1024, //3g
          // 最多可上传几个文件，默认为 5
          maxNumberOfFiles: 20,
          async customUpload(file, insertFn) {
            alert('已经开始上传了')
            let path = PATH_wangEditor_img_vid + getUuid() + '/' + file.name
            let { res, ok, err } = await putBuffer('put', path, file, true)
            if (ok) {
              insertFn(res, '')
            } else {
              alert(err)
            }
          }
        }
      },
      // 选中公式时的悬浮菜单
      hoverbarKeys: {
        formula: {
          menuKeys: ['editFormula'] // “编辑公式”菜单
        },
        image: {
          // 清空 image 元素的 hoverbar
          menuKeys: [
            'imageWidth30',
            'imageWidth50',
            'imageWidth100',
            'editImage',
            'viewImageLink',
            'deleteImage',
            'menu_del_img_from_oss'
          ]
        },
        video: {
          menuKeys: ['enter', 'editVideoSize', 'menu_del_img_from_oss']
        }
      }
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value

      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
      eventBus.emit('ev_editor', editor)
      console.log(editor.getConfig().hoverbarKeys)
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    }
  }
}
</script>

<style lang="less">
/* 暗色主题 */
// *{
//     --w-e-textarea-bg-color: #333;
//     --w-e-textarea-color: #fff;
//     /* ...其他... */
// }
</style>
